import {useMutation, useQueryClient} from "@tanstack-react-query"
import toast from "react-hot-toast"


const useFollow = () => {
    const queryClient = useQueryClient()

    const {mutate: follow, isPending} = useMutation({
        mutationFn: async (userId) => {
            try {
                // NOTE: POST to backend api
                const res = await fetch(`/api/users/follow/${userId}`, {
                    method: "POST",
                })

                const data = await res.json()
                if (!res.ok) {
                    throw new Error(data.error || "Something went wrong")
                }
                return
            }catch(error) {
                throw new Error("Error in useFollow hook: "+error.message)
            }
        },

        onSuccess: () => {
            Promise.all([
                queryClient.invalidateQueries({
                    queryKey: ["suggestedUsers"]
                }),
                queryClient.invalidateQueries({
                    queryKey: ["authuser"]
                })
            ])
        },
        
        onError: (error) => {
            toast.error("Error in useFollow hook" + error.message)
        },
    })

    return {follow, isPending}
}

export default useFollow